package utils

import (
	"io"
	"net/http"
	"os"
	"path/filepath"
)

func DownloadFile(url string, path string) {
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	out, err := os.Create(path)
	if err != nil {
		panic(err)
	}
	defer out.Close()

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		panic(err)
	}
}

func SaveHttpImage(url string, dir string, path string) (fullPath string) {
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	contentType := resp.Header.Get("Content-Type")
	var fileExt string
	switch contentType {
	case "image/jpeg":
		fileExt = ".jpg"
	case "image/png":
		fileExt = ".png"
	default:
	}
	path += fileExt
	fullPath = filepath.Join(dir, path)
	os.MkdirAll(dir, 0777)
	os.Chmod(dir, 0777)
	defer resp.Body.Close()
	out, err := os.Create(fullPath)
	if err != nil {
		panic(err)
	}
	defer out.Close()
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		panic(err)
	}
	return
}
